<!--
 @description 帮助中心搜索
 @fileName List.vue
 @author zengqiongying
 @created 2022/02/22 14:15:03
-->
<template>
  <div class="search">
    <Header
      ref="header"
      v-model="searchValue"
      fixed
      arrow
      show-search
      :focus="focus"
      @input="inputHandle"
      @search="enterHandle"
      @focus="focusHandle"
      @blur="blurHandle"
      @clear="clearHandle"
    />
    <div class="helpl-search-page">
      <ResultList v-if="!show && !loading" ref="refResult" :define-range-ids="defineRangeIds" :define-search="!!defineId" :search-value="searchValue" page-type="search" />
      <div v-show="show" class="search-panne">
        <div v-if="historyList.length>0">
          <div class="history-list">
            <Scroll vertical style="max-height: 100vh;">
              <div class="history-title">
                <span>搜索历史</span>
                <svg-icon icon-class="shanchulajixiang-solid" @click.native.stop="closeRemoveHandle" />
              </div>
              <div class="history-tags">
                <Tag v-for="(h,i) in historyList" :key="h.label + i" :label="h.label" :value="h.label" button closeable long-press @click="clickTagHandle(h)" @close="closeRemoveHandle(i)" />
              </div>
            </Scroll>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import Header from '../components/Header'
import Tag from '@/components/Tag'
import Scroll from '@/components/Scroll'
import ResultList from './Result'
import { getCatalogueIdList } from '@/apis/index'
import { mapMutations, mapGetters } from 'vuex'
function throttle(fn, delay = 200) {
  let id
  return (...args) => {
    if (id) {
      return
    }
    id = setTimeout(() => {
      fn(...args)
      id = null
    }, delay)
  }
}
export default {
  name: 'HelpCenterSearch',
  components: {
    Header,
    Tag,
    Scroll,
    ResultList
  },
  data() {
    return {
      defineId: this.$route.query.defineId, // 自定义目录ID
      defineRangeIds: [],
      loading: true,
      show: true,
      searchValue: '',
      activeNav: 'new',
      navList: [
        { label: '最近更新', value: 'new' },
        { label: '点赞量', value: 'like' },
        { label: '浏览量', value: 'view' }
      ],
      // 历史列表
      historyList: [],
      // 获取搜索结果函数
      getFun: throttle(this.getContentList)
    }
  },
  computed: {
    ...mapGetters('nav', ['focus'])
  },
  watch: {
    show(v) {
      if (v) {
        sessionStorage.setItem('forbid_help', true)
        document.body.style.overflow = 'hidden'
        // this.$refs.navFilter.closeHandle()
        // this.$refs.navFilter.showNav = true
      } else {
        sessionStorage.removeItem('forbid_help')
        document.body.style.overflow = 'inherit'
      }
    }
  },
  async created() {
    this.show = false
    this.loading = true
    if (this.defineId) {
      this.defineRangeIds = await getCatalogueIdList(this.defineId)
    }
    this.loading = false
  },
  mounted() {
    this.updateFocus(false)
  },
  beforeDestroy() {
    this.updateFocus(true)
  },
  activated() {
    if (this.searchValue === '') {
      this.searchValue = ''
      this.updateFocus(false)
      this.clearHandle()
    }
  },
  deactivated() {
    this.show = false
  },
  beforeRouteLeave(to, from, next) {
    const names = ['HelpCenterDetail']
    if (!names.includes(to.name)) {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  methods: {
    ...mapMutations('nav', ['updateFocus']),
    // 输入
    inputHandle(v) {
      this.getFun(v)
    },
    enterHandle(_value) {
      if (_value === '') return
      let value = _value
      let label = value
      let type = 'string'
      if (typeof _value === 'object') {
        label = _value.description
        value = JSON.stringify(_value)
        type = 'object'
      }
      for (let i = 0; i < this.historyList.length; i++) {
        const v = this.historyList[i]
        if (v.value === value) {
          this.historyList.splice(i, 1)
          break
        }
      }
      const item = {
        label: label,
        value,
        type
      }
      this.historyList.unshift(item)
      localStorage.setItem('helpHistoryList', JSON.stringify(this.historyList))
      this.show = false
      this.$refs.header.blur()
      // 调用
      this.$nextTick(() => {
        this.broadcast('refresh', 'refresh')
      })
    },
    // 更新historyList
    updateHistoryList() {
      const historyList = localStorage.getItem('helpHistoryList')
      if (historyList) {
        this.historyList = JSON.parse(historyList)
      } else {
        this.historyList = []
      }
    },
    // 删除搜索历史
    closeRemoveHandle(i) {
      if (!/^\d+$/.test(i)) {
        localStorage.removeItem('helpHistoryList')
        this.historyList = []
      } else {
        this.historyList.splice(i, 1)
        localStorage.setItem('helpHistoryList', JSON.stringify(this.historyList))
      }
    },
    clearHandle() {
      this.$refs.header.getFocus()
    },
    clickTagHandle(v) {
      if (v.type === 'object') {
        this.searchValue = v.label
        this.enterHandle(JSON.parse(v.value))
      } else {
        this.searchValue = v.label
        this.enterHandle(v.value)
      }
    },
    focusHandle() {
      this.show = true
      this.updateHistoryList()
    },
    blurHandle() {
      // setTimeout(() => {
      // this.show = false
      // }, 0)
    }

  }
}

</script>
<style lang="less" scoped>
.search{
  min-height: 100vh;
  width: 100vw;
  background-color: #fff;
  padding-top: 44PX;
  box-sizing: border-box;
  .helpl-search-page{
    position: relative;
  }
  .search-panne{
    position: absolute;
    z-index: 999;
    top: 0;
    left: 0;
    width: 100%;
    height: calc(100vh - 44PX);
    padding: 0px 12px;
    background-color: #fff;
    box-sizing: border-box;
    .history-list{
      background-color: #fff;
      .history-title{
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #333333;
        line-height: 20px;
        letter-spacing: 1px;
        font-size: 14px;
        font-weight: bold;
        padding: 20px 0;
        p{
          font-size: 14px;
          color: #333;
          font-weight: 500;
        }
        svg{
          font-size: 14px;
          color: #BDBDBD;
          fill: #BDBDBD;
        }
      }
      .history-tags{
        &>*{
          margin: 0 10px 10px 0;
        }
      }
    }
  }
}
</style>
